package com.googlecode.gwtbb.client.only.widget.form.entry;

import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.googlecode.gwtbb.client.shared.util.ObjectUtils0;
import com.googlecode.gwtbb.client.shared.validation.FieldId;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Abraham Grief
 * @version $Id$
 * @since Jul 27, 2008
 */
public class LabeledCompoundRadioGroupFormEntry extends LabeledFormEntry {
	final private List<ValueRadioButton> entryRadioGroup;
	private List<WidgetCell> widgetCells;

	public LabeledCompoundRadioGroupFormEntry(FieldId fieldId, String defaultValue, int row, int col, String labelText, List<ValueRadioButton> entryRadioGroup) {
		super(fieldId, defaultValue, row, col, labelText);
		this.entryRadioGroup = entryRadioGroup;
		clearValue();
	}

	public List<ValueRadioButton> getEntryRadioGroup() {
		return entryRadioGroup;
	}

	@Override
	public List<WidgetCell> getWidgetCells() {
		if (widgetCells == null) {
			widgetCells = new ArrayList<WidgetCell>(2);
			Panel labelCell = new VerticalPanel();
			labelCell.add(getFailurePanel());
			labelCell.add(getLabel());
			widgetCells.add(new WidgetCell(labelCell, getLabelRow(), getLabelCol(), getLabelRowSpan(), getLabelColSpan(), getLabelHorizontalAlignment(), getLabelVerticalAlignment()));
			for (int i = 0; i < entryRadioGroup.size(); i++) {
				ValueRadioButton vbr = entryRadioGroup.get(i);
				widgetCells.add(new WidgetCell(vbr, getEntryRow(), getEntryCol() + i, getEntryRowSpan(), getEntryColSpan(), getEntryHorizontalAlignment(), getEntryVerticalAlignment()));
			}
		}
		return widgetCells;
	}

	/**
	 * This has no singular entry widget.
	 *
	 * @return null
	 */
	public Widget getEntryWidget() {
		return null;
	}

	public String getValue() {
		for (ValueRadioButton vbr : entryRadioGroup)
			if (vbr.getValue())
				return vbr.getInnerValue();
		return null;
	}

	public void setValue(String value) {
		for (ValueRadioButton vbr : entryRadioGroup)
			vbr.setValue(ObjectUtils0.nullSafeEquals(vbr.getInnerValue(), value));
	}
}